package cn.springmix.core.exception;

import cn.springmix.base.lang.entity.R;
import cn.springmix.base.lang.exception.BaseException;
import cn.springmix.base.lang.exception.GlobalCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xufeng
 * 全局异常处理
 */
@Slf4j
@RestControllerAdvice
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class GlobalExceptionHandler {


    /**
     * 未捕捉的异常统一处理
     */
    @ExceptionHandler(Exception.class)
    public R<?> handleException(Exception e) {
        R result = new R<>();
        result.setCode(500);
        result.setMessage(e.getMessage());
        log.error(String.format("未知异常:%s", e.getMessage()), e);
        return result;
    }

    /**
     * 统一业务异常统一处理方法
     */
    @ExceptionHandler(BaseException.class)
    public R<?> handleServiceException(BaseException e) {
        R result = new R<>();
        result.setCode(e.getErrCode());
        result.setMessage(e.getMessage());
        log.error(String.format("业务异常:%s", e.getMessage()), e);
        return result;
    }


    /**
     * 统一处理参数校验错误异常(Spring接口数据绑定验证)
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<?> processValidException(MethodArgumentNotValidException e) {
        List<String> errorStringList = e.getBindingResult().getAllErrors()
                .stream().map(ObjectError::getDefaultMessage).collect(Collectors.toList());
        String errorMessage = String.join("; ", errorStringList);
        log.error(String.format("参数异常:%s", e.getMessage()), e);
        return R.systemException(GlobalCodeEnum.GL_FAIL_9998.getCode(),
                errorMessage);
    }

    /**
     * 非法参数类型异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseStatus(value = HttpStatus.OK)
    public R<?> handleMethodArgumentTypeMismatchExceptionHandler(MethodArgumentTypeMismatchException e) {
        log.error("参数异常:方法:{},字段:{},参数:{},错误信息:{}", e.getParameter().getMethod(), e.getName(), e.getValue(), e.getMessage());
        return R.systemException(GlobalCodeEnum.GL_FAIL_9998.getCode(),
                "参数类型异常" + e.getName() + "," + e.getValue());
    }

    /**
     * 统一处理参数校验错误异常(非Spring接口数据绑定验证)
     */
    @ExceptionHandler(BindException.class)
    public R<?> processValidException(BindException e) {
        //获取校验错误结果信息，并将信息组装
        List<String> errorStringList = e.getBindingResult().getAllErrors()
                .stream().map(ObjectError::getDefaultMessage).collect(Collectors.toList());
        String errorMessage = String.join("; ", errorStringList);
        log.error(String.format("参数异常:%s", e.getMessage()), e);
        return R.systemException(GlobalCodeEnum.GL_FAIL_9998.getCode(),
                errorMessage);
    }

    /**
     * 统一处理参数校验错误异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public R<?> processValidException(IllegalArgumentException e) {
        String errorMessage = String.join("; ", e.getMessage());
        log.error(String.format("参数异常:%s", e.getMessage()), e);
        return R.systemException(GlobalCodeEnum.GL_FAIL_9998.getCode(),
                errorMessage);
    }

    /**
     * 统一处理参数校验错误异常
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public R<?> processValidException(HttpRequestMethodNotSupportedException e) {
        String[] supportedMethods = e.getSupportedMethods();
        String errorMessage = "此接口不支持" + e.getMethod();
        if (supportedMethods != null) {
            errorMessage += "（仅支持" + String.join(",", supportedMethods) + "）";
        }
        log.error(String.format("请求格式异常:%s", errorMessage), e);
        return R.systemException(GlobalCodeEnum.GL_FAIL_9998.getCode(),
                errorMessage);
    }


    /**
     * json序列化失败
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public R<?> getPostException(HttpMessageNotReadableException e) {
        log.error(String.format("JSON序列化失败:%s", e.getMessage()), e);
        return R.systemError(GlobalCodeEnum.GL_FAIL_10000);
    }
}
